# 最大连续1的个数III: https://leetcode-cn.com/problems/max-consecutive-ones-iii/

# 和 I 的第二种写法是类似的
class Solution:
    def longestOnes(self, nums: list, k: int) -> int:
        i = j = 0
        n = len(nums)
        ZeroCnt = 0
        ans = 0
        while j < n:
            if nums[j] == 0:
                if ZeroCnt < k:
                    ZeroCnt += 1
                else:
                    # 计算和
                    ans = max(ans, j - i)
                    # 更新i
                    while nums[i] != 0:
                        i += 1
                    i += 1
            j += 1            

        return max(ans, j - i)



from collections import deque
class Solution:
    def longestOnes(self, nums: list, k: int) -> int:
        i = j = 0
        n, ans = len(nums), 0
        ZeroCnt = deque()
        while j < n:
            if nums[j] == 0:
                if len(ZeroCnt) < k:
                    ZeroCnt.append(j)
                else:
                    # 计算和
                    ans = max(ans, j - i)
                    # 更新i
                    i = ZeroCnt.popleft() + 1 if  k > 0 else j + 1
                    ZeroCnt.append(j)
                    
            j += 1

        return max(ans, j - i)


from collections import deque
class Solution:
    def longestOnes(self, nums: list, k: int) -> int:
        i = j = 0
        n, ans = len(nums), 0
        ZeroCnt = deque()
        while j < n:
            if nums[j] == 0:
                if len(ZeroCnt) >= k:
                    # 计算和
                    ans = max(ans, j - i)
                    # 更新i
                    i = ZeroCnt.popleft() + 1 if  k > 0 else j + 1
                ZeroCnt.append(j)
                    
            j += 1

        return max(ans, j - i)